<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="72px"
			class="queryForms">
			<el-form-item label="设备名称" prop="deviceName">
				<el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="设备编号" prop="deviceNumber">
				<el-input v-model="queryParams.deviceNumber" placeholder="请输入设备编号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="设备型号" prop="deviceModel">
				<el-input v-model="queryParams.deviceModel" placeholder="请输入设备型号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="检定周期" prop="periodValidity">
				<el-select v-model="queryParams.periodValidity">
					<el-option v-for="item in timelist" :key="item.id" :value="item.id" :label="item.name"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="审批状态" prop="approvalStatus">
				<el-select v-model="queryParams.approvalStatus" placeholder="请选择">
					<el-option v-for="dict in dict.type.default_approve" :key="dict.value" :label="dict.label"
						:value="dict.value"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleSubmits"
					v-hasPermi="['quality:planlist:submit']">提交</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleApprove({})"
					v-hasPermi="['quality:planlist:approve']">审批</el-button>
			</el-col>
			<CreateForm :ids="ids" :rows="rows" formtype="t_quality_planlist" />
			<right-toolbar menuNames="planlist39" @changeTableData="changeTableData" :showSearch.sync="showSearch"
				@queryTable="handleQuery" :columns.sync="columns" perm="quality:planlist:index"></right-toolbar>
		</el-row>

		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''"
			class="informationTab" ref="eleTab">
			<!-- lazy :load="loadListDes" -->
			<el-table row-class-name="row_class_name" @mousedown.native="mousedownTable" @row-click="row_click"
				@cell-mouse-enter="cell_mouse_enter" @cell-mouse-leave="cell_mouse_leave" @mouseup.native="mouseupTable"
				@mouseleave.native="mouseupTable" ref="multipleTable" v-loading="loading" :data="planList"
				@selection-change="handleSelectionChange" row-key="id"
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55">
					<template slot-scope="scope">
						<div>{{ scope.row.sort }}</div>
					</template>
				</el-table-column>
				<el-table-column label="记录编号" align="left" prop="recordNumber" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[0].visible" />
				<el-table-column label="设备名称" align="left" prop="deviceName" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[1].visible" />
				<el-table-column label="设备编号" align="left" prop="deviceNumber" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[2].visible" />
				<el-table-column label="设备型号" prop="deviceModel" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[3].visible" />
				<el-table-column label="审批状态" align="center" prop="approvalStatus" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[14].visible">
					<template slot-scope="scope">
						<!-- <div @click="showApproveList(scope.row)">
							<dict-tag :options="dict.type.default_approve" :value="scope.row.approvalStatus" />
						</div> -->
						<el-tag type="info" v-if="scope.row.approvalStatus === '0'" class="disableClick">
							<dict-tag :options="dict.type.default_approve" :value="scope.row.approvalStatus" />
						</el-tag>
						<el-tag v-if="scope.row.approvalStatus === '1'" @click="showApproveList(scope.row)"
							class="clickable">
							<dict-tag :options="dict.type.default_approve" :value="scope.row.approvalStatus" />
						</el-tag>
						<el-tag type="success" v-if="scope.row.approvalStatus === '2'"
							@click="showApproveList(scope.row)" class="clickable">
							<dict-tag :options="dict.type.default_approve" :value="scope.row.approvalStatus" />
						</el-tag>
						<el-tag type="danger" v-if="scope.row.approvalStatus === '3'"
							@click="showApproveList(scope.row)" class="clickable">
							<dict-tag :options="dict.type.default_approve" :value="scope.row.approvalStatus" />
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="精度等级" align="center" prop="accuracyClass" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[4].visible">
					<template slot-scope="scope">
						<dict-tag :options="dict.type.accuracy_level" :value="scope.row.accuracyClass" />
					</template>
				</el-table-column>
				<el-table-column label="生产厂及国别" prop="manufacturingPlant" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[5].visible" />
				<el-table-column label="完好状态" prop="intactState" min-width="150" :show-overflow-tooltip="true"
					align="center" v-if="columns[6].visible">
					<template slot-scope="scope">
						<dict-tag :options="dict.type.measure_intact_state" :value="scope.row.intactState" />
					</template>
				</el-table-column>
				<el-table-column label="生产日期" align="center" prop="producedTime" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[7].visible">
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.producedTime, "{y}-{m}-{d}") }}</span>
					</template>
				</el-table-column>
				<el-table-column label="购置日期" align="center" prop="purchaseTime" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[8].visible">
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.purchaseTime, "{y}-{m}-{d}") }}</span>
					</template>
				</el-table-column>
				<el-table-column align="center" label="检定日期" prop="lastAppraisalDate" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[9].visible" />
				<el-table-column label="检定周期" align="center" prop="periodValidity" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[10].visible">
					<template slot-scope="scope">
						<div v-if="scope.row.periodValidity == 1">一年</div>
						<div v-if="scope.row.periodValidity == 2">半年</div>
						<div v-if="scope.row.periodValidity == 3">一个月</div>
					</template>
				</el-table-column>
				<el-table-column label="送检日期" align="center" prop="inspectDate" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[11].visible" />
				<el-table-column label="下发状态" prop="issueStatus" min-width="150" :formatter="issueStatusFormatter"
					:show-overflow-tooltip="true" v-if="columns[12].visible" align="center" />
				<el-table-column label="备注" prop="remark" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[13].visible" />
				<el-table-column label="操作" align="left" class-name="small-padding fixed-width" fixed="right"
					width="140">
					<template slot-scope="scope">
						<section v-if="scope.row.hasChildrens">
							<!-- 未下发，已审批 -->
							<el-button v-show="scope.row.issueStatus == '0' && scope.row.approvalStatus == '2'"
								size="mini" type="text" icon="el-icon-bottom-right" @click="handleIssue(scope.row)"
								v-hasPermi="['quality:planlist:distribute']">下发</el-button>
							<el-button size="mini" type="text" icon="el-icon-circle-check"
								@click="handleSubmit(scope.row)"
								v-show="scope.row.approvalStatus == '0' || scope.row.approvalStatus == '3'"
								v-hasPermi="['quality:planlist:submit']">提交</el-button>
							<!-- 审批中显示 -->
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleApprove(scope.row)"
								v-show="scope.row.approvalStatus == '1' && scope.row.existApprovalStatus == '0'"
								v-hasPermi="['quality:planlist:approve']">审批</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<pagination menuNames="Pagination42" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改生产计划对话框 -->
		<el-dialog title="检定计划" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
			<el-form ref="form" class="add-form1" :model="form" :rules="rules" label-width="100px">
				<el-form-item label="记录编号" prop="recordNumber">
					<el-input v-model="form.recordNumber" placeholder="请输入记录编号" maxlength="20" show-word-limit />
				</el-form-item>
				<el-form-item label="编号" prop="serialNumber">
					<el-input v-model="form.serialNumber" placeholder="请输入编号" maxlength="20" show-word-limit />
				</el-form-item>
				<el-form-item label="送检日期" prop="inspectDate">
					<el-date-picker clearable v-model="form.inspectDate" type="date" value-format="yyyy-MM-dd"
						placeholder="请选择送检日期"> </el-date-picker>
				</el-form-item>
				<el-form-item label="备注" prop="remark" style="width: 100%">
					<el-input v-model="form.remark" type="textarea" placeholder="请输入备注" maxlength="100"
						show-word-limit />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 审批弹框 -->
		<el-dialog title="审批" :visible.sync="openApprove" width="900px" append-to-body v-dialogDrag>
			<ApproveTemplete @cancelApprove="cancelApprove" :openApprove="openApprove"></ApproveTemplete>
		</el-dialog>
		<!-- 审批流程弹框 -->
		<el-dialog title="审批流程" :visible.sync="openRecords" width="900px" append-to-body v-dialogDrag>
			<RecordsTemplete :approveRecord="approveRecord"></RecordsTemplete>
		</el-dialog>
	</div>
</template>

<script>
import { listPlanList, getPlanList, delPlanList, listPlanlistChild, issuePlan, submitPlan, planApprove } from "@/api/quality/planlist"
import CreateForm from "@/views/components/CreateForm"
import { approvalRecord } from "@/api/productTechnology/productTechnologyVersions"
import ApproveTemplete from "@/views/components/ApproveTemplete"
import RecordsTemplete from "@/views/components/RecordsTemplete"
import { mapGetters } from "vuex"
import { getcolumn } from "@/api/selectList"
import searchStateMixin from '@/layout/mixin/searchStateMixin.js'   
export default {
	name: "Planlist",
	dicts: ["accuracy_level", "measure_intact_state", "period_validity", "authenticate_status", "default_approve"],
	components: { ApproveTemplete, RecordsTemplete, CreateForm },
mixins: [searchStateMixin], 
	data() {
		return {
			timelist: [
				{
					id: "1",
					name: "一年"
				},
				{
					id: "2",
					name: "半年"
				},
				{
					id: "3",
					name: "一个月"
				}
			],
			isMousedownTable: false, //是否按下表格
			currentEnterRow: null, //当前移入的行数据
			eleTabTop: 0, //表格容器距浏览器顶部距离
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			rows: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 生产计划表格数据
			planList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				idList: undefined,
				pageNum: 1,
				pageSize: 10,
				deviceName: undefined,
				lastAppraisalDate: undefined,
				periodValidity: undefined,
				authenticateStatus: undefined,
				deviceModel: undefined,
				deviceNumber: undefined,
				approvalStatus: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				recordNumber: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
				serialNumber: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
				inspectDate: [{ required: true, message: "设备名称不能为空", trigger: "blur" }]
			},
			treetablekey: Math.random(),
			// 更新树刷新
			treeMap: new Map(),
			// 审批数据
			openApprove: false,
			approveRow: undefined,
			// 审批流程
			openRecords: false,
			approveRecord: [],
			// 列信息
			columns: [
				{ key: 0, label: `记录编号`, visible: true },
				{ key: 1, label: `设备名称`, visible: true },
				{ key: 2, label: `设备编号`, visible: true },
				{ key: 3, label: `设备型号`, visible: true },
				{ key: 4, label: `精度等级`, visible: true },
				{ key: 5, label: `生产厂及国别`, visible: true },
				{ key: 6, label: `完好状态`, visible: true },
				{ key: 7, label: `生产日期`, visible: true },
				{ key: 8, label: `购置日期`, visible: true },
				{ key: 9, label: `检定日期`, visible: true },
				{ key: 10, label: `检定周期`, visible: true },
				{ key: 11, label: `送检日期`, visible: true },
				{ key: 12, label: `下发状态`, visible: true },
				{ key: 13, label: `备注`, visible: true },
				{ key: 14, label: `审批状态`, visible: true }
			]
		}
	},
	computed: {
		...mapGetters(["sidebar"])
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	watch: {
		"$route.query": {
			handler(newQuery, oldQuery) {
				if (newQuery.queryData) {
					if (Object.keys(newQuery.queryData).length === 0) {
						this.resetForm("queryForm")
						// this.getSize()
					} else {
						this.queryParams = { ...this.queryParams, ...JSON.parse(newQuery.queryData) }
						// this.getSize()
					}
				} this.getSize()
			},
			immediate: true, // 立即执行一次
			deep: true // 深度监听
		}
	},
	activated() {
		// this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	created() {
		// this.getSize()
	},
	methods: {
		getSize() {
			getcolumn({ pageName: "Pagination42" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		/** 查询生产计划列表 */
		getList() {
			this.loading = true
			listPlanList(this.queryParams).then(response => {
				response.rows.forEach((item, index) => {
					item.hasChildrens = true
					item.sort = index + 1
					this.$refs.multipleTable.toggleRowExpansion(item, false);
					item.children.forEach((items, indexs) => {
						items.sort = indexs + 1
						items.hasChildrens = false
						items.id = "c" + items.id
					})
				})
				this.planList = response.rows
				this.total = response.total
				this.loading = false
			})
		},
		// 获取列表子菜单
		async loadListDes(tree, treeNode, resolve) {
			if (!this.treeMap.has(tree.id)) {
				this.treeMap.set(tree.id, {
					treeNode,
					resolve
				})
			}
			let data = {
				measuringEquipmentVerificationId: tree.id,
				productName: this.queryParams.productName,
				productModel: this.queryParams.productModel,
				productNumber: this.queryParams.productNumber
			}
			let ret = await listPlanlistChild(data)
			ret.rows.forEach((item, index) => {
				// 父子id会冲突
				item.id = "c" + item.id
				item.sort = index + 1
			})
			resolve(ret.rows)
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				recordNumber: undefined,
				serialNumber: undefined,
				inspectDate: undefined,
				remark: undefined
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.saveSearchState() 
			this.getList()
			this.treetablekey = Math.random()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.queryParams.authenticateStatus = undefined
			this.queryParams.approvalStatus = undefined
			this.clearSearchCache() 
			this.handleQuery()
		},
		// 表格按下
		mousedownTable(event) {
			const target = event.target
			// 判断target的class属性确定是否点击在复选框上
			if (target.classList.contains("el-checkbox__inner")) {
				this.currentEnterRow && this.$refs.multipleTable.toggleRowSelection(this.currentEnterRow)
				this.isMousedownTable = true
			}
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.multipleTable.toggleRowSelection(row)
				let flag = this.ids.some(item => item == row.id)
				if (row.hasChildrens) {
					row.children.forEach(items => {
						if (flag) {
							this.$refs.multipleTable.toggleRowSelection(items, true)
						}
					})
				}
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.multipleTable.doLayout()
			})
		},

		// 进入单元格
		cell_mouse_enter(row, column, cell, event) {
			this.isMousedownTable && this.$refs.multipleTable.toggleRowSelection(row)
			this.currentEnterRow = row
		},
		// 离开单元格
		cell_mouse_leave(row, column, cell, event) {
			this.currentEnterRow = null
		},
		// 鼠标弹起或者离开表格
		mouseupTable(d) {
			this.isMousedownTable = false
		},
		// 表格每行样式
		row_class_name({ row, rowIndex }) {
			return this.rows.find(v => v.id == row.id) ? "selected" : ""
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.rows = selection
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset()
			this.open = true
			this.title = "添加生产计划"
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset()
			const id = row.id || this.ids
			getPlanList(id).then(response => {
				this.form = response.data
				this.open = true
				this.title = "修改生产计划"
			})
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					this.form.ids = this.ids
					addPlan(this.form).then(response => {
						this.$modal.msgSuccess("操作成功")
						this.open = false
						this.getList()
					})
				}
			})
		},
		// 下发
		handleIssue(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确定下发测量设备检定计划给生产部？")
				.then(function () {
					return issuePlan({ id: ids })
				})
				.then(() => {
					localStorage.setItem("todoMessage", 'plan1')
					this.getList()
					this.$modal.msgSuccess("操作成功")
				})
				.catch(() => { })
		},
		/** 删除按钮操作 */
		// handleDelete(row) {
		//   const ids = row.id || this.ids;
		//   this.$modal
		//     .confirm("是否确认删除生产计划的数据项？")
		//     .then(function () {
		//       return delPlanList(ids);
		//     })
		//     .then(() => {
		//       this.getList();
		//       this.$modal.msgSuccess("删除成功");
		//     })
		//     .catch(() => {});
		// },
		// 跳转到附件
		handleJump(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: row.id,
					typeId: 2
				}
			})
		},
		// 下发状态
		issueStatusFormatter(row) {
			if (row.issueStatus === "0") {
				return "未下发"
			} else if (row.issueStatus === "1") {
				return "已下发"
			} else {
				return ""
			}
		},
		handleSubmits() {
			let checkp = this.rows.every(item => {
				return typeof item.id == "number"
			})
			if (!checkp) {
				this.$modal.msg("只能选择父级产品进行提交")
				return false
			}
			const _this = this
			this.$modal
				.confirm(`是否确认提交数据？`)
				.then(function () {
					return submitPlan({
						workIds: _this.ids,
						workflowType: "10"
					})
				})
				.then(() => {
					_this.getList()
					localStorage.setItem("todoMessage", 'plan2')
					_this.$modal.msgSuccess("提交成功")
					_this.$refs.multipleTable.clearSelection()
				})
				.catch(() => { })
		},
		// 列表父级提交
		handleSubmit(row) {
			this.$modal
				.confirm("是否确认提交数据项？")
				.then(function () {
					let data = {
						workId: row.id,
						workflowType: "10",
						// 1是提交，3是重复提交
						submitStatus: row.approvalStatus == "0" ? "1" : "2"
					}
					return submitPlan(data)
				})
				.then(() => {
					this.getList()
					localStorage.setItem("todoMessage", 'plan3')
					this.$modal.msgSuccess("操作成功")
				})
				.catch(() => { })
		},
		// 审批
		handleApprove(row) {
			if (row.id) {
				this.approveRow = {
					id: row.id,
					status: row.hasChildrens ? true : false,
					repairId: row.repairId
				}
				this.openApprove = true
			} else {
				this.approveRow = {}
				let checkp = this.rows.every(item => {
					return typeof item.id == "number"
				})
				if (!checkp) {
					this.$modal.msg("只能选择父级产品进行审批")
					return false
				}
				this.openApprove = true
			}
		},

		// 审批取消
		async cancelApprove(ret) {
			if (!ret.flag) {
				this.openApprove = false
				return false
			}
			let data = {
				approvalStatus: ret.approvalStatus,
				causeRejection: ret.causeRejection,
				workflowType: "10"
			}
			this.approveRow.id ? (data.id = this.approveRow.id) : (data.ids = this.ids)
			const loading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			let res = await planApprove(data)
			if (res.code == 200) {
				this.$modal.msgSuccess("操作成功")
				this.getList()
				loading.close();
				localStorage.setItem("todoMessage", 'plan6')
				this.$refs.multipleTable.clearSelection()
			} else {
				loading.close();
			}
			this.openApprove = false
		},
		// 获取审批详情
		showApproveList(row) {
			if (row.approvalStatus == "0") {
				return false
			}
			this.openRecords = true
			approvalRecord({
				id: row.id,
				workflowType: "10"
			}).then(res => {
				this.openRecords = true
				this.approveRecord = res.data
			})
		}
	}
}
</script>
<style lang="scss" scoped>
::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 140px !important;
}
</style>
